<script setup lang="ts">
import { OrderType } from '@/enums'
import { uploadImage } from '@/services/consult'
import type { Image } from '@/types/consult'
import { showToast } from 'vant'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { ref } from 'vue'

defineProps<{
  status?: OrderType
}>()

const text = ref('')
const emits = defineEmits<{
  (e: 'sendText', text: string): void
  (e: 'sendImg', img: Image): void
}>()
// 发生消息 传递给父组件
const sendMsg = () => {
  if (!text.value) return showToast('请输入要咨询的信息')
  emits('sendText', text.value)
  // 清空输入框
  text.value = ''
}

// 发送图片消息
const afterRead: UploaderAfterRead = async (obj) => {
  // 1. 多选判断
  if (Array.isArray(obj)) return
  // 2. 非空判断
  if (!obj.file) return
  // 3. 上传请求
  const res = await uploadImage(obj.file)
  // 4. 通知父组件
  emits('sendImg', res.data)
}
</script>

<template>
  <div class="room-action">
    <van-field
      type="text"
      class="input"
      :border="false"
      placeholder="问医生"
      autocomplete="off"
      :disabled="status !== OrderType.ConsultChat"
      v-model.trim="text"
      @keyup.enter="sendMsg"
    ></van-field>
    <van-uploader
      :preview-image="false"
      :disabled="status !== OrderType.ConsultChat"
      :after-read="afterRead"
    >
      <cp-icon name="consult-img" />
    </van-uploader>
  </div>
</template>

<style lang="scss" scoped>
.room-action {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1;
  box-sizing: border-box;
  .input {
    background-color: var(--cp-bg);
    border: none;
    border-radius: 25px;
    margin-right: 10px;
    padding: 8px 15px;
  }
  .cp-icon {
    width: 24px;
    height: 24px;
  }
}
</style>
